﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@algo-plus.co.uk website<http://www.algo-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using FinPlusCompCore;
using FinPlusAssembler;
using FinPlusInterfaces;
using s = FinPlusBaseMath.Statistics;

namespace FinPlusCompAlgo
{
    public class AlgPlusRecentAverage : FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }

        public override IPods Adapter { get { return _adapter; } }

        private enum Params { RAvg }
        private IFinPlusComp _feed;
        private readonly IPods _adapter;
        private readonly IList<string> _averages;
        private readonly string _name, _value;
        private readonly short _from, _decimalPlaces;

        //construct
        public AlgPlusRecentAverage(IFinPlusComp feed, short from, string name, string value, IList<string> averages, short decimalPlaces) 
        {
            _feed = feed;
            _from = from;
            _name = name;
            _value = value;
            _averages = averages;
            _decimalPlaces = decimalPlaces;
            _adapter = IOC.New<IPods>();
            CalcMovingAverages(feed);
        }

        //common control interface
        public override void CmdExecute(IPod command)
        {
            try
            {
                CmdCapture(command);
            }
            catch (CmdExecuteException e)
            {
                IsValid = Level.Error.Log(Id, Config, e.Message, e);
            }
        }

        public override void Dispose()
        {
            if (_feed != null)
                _feed.Dispose();
        }

        //private
        private void CalcMovingAverages(IFinPlusComp feed)
        {
            _feed = feed;
            foreach (var average in _averages)
                CalcMovingAverage(average);
        }

        private void CalcMovingAverage(string period)
        {
            var res = _feed.Adapter.ToList(_name, _value).First().Where(i => i.Index >= _from);
            var pod = IOC.New<IPod>(Params.RAvg.ToString(), "-1");
            var reg = s.RecentAverage(res.Select(i => (double)i.Object).ToArray<double>(), (int)period.IntParse());
            pod[string.Format("{0}|{1}", Params.RAvg.ToString(), period)] = Math.Round(reg, _decimalPlaces);
            _adapter.Add(pod);
        }
    }
}
